
(function () {

    $.extend($.fn.datagrid.methods, {
        // 扩展实现DataGrid单元格编辑模式,param有两个属性：field、index
        exEditCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        },

        // 扩展实现DataGrid获取当前编辑行指定编辑器控件,param有两个属性：itemName、editingIndex（可选）
        exGetControl: function (jq, param) {
            var result;
            if (jq.length <= 0) {
                return result;
            }

            var itemName = param;
            if (param.itemName) {
                itemName = param.itemName;
            }

            var editingIndex = jq[0].exEditingRowIndex;
            if (param.editingIndex >= 0) {
                editingIndex = param.editingIndex;
            }
            else if (!(editingIndex >= 0)) {
                editingIndex = jq.datagrid('getRowIndex', jq.datagrid('getSelected'));
            }

            if (itemName == null
                || editingIndex == undefined || editingIndex == null || editingIndex < 0) {
                return result;
            }

            var editor = jq.datagrid('getEditor', { index: editingIndex, field: itemName });
            if (!editor || !editor.target || editor.target.length <= 0) {
                return result;
            }

            return editor.target[0];
        }
    });

    $.extend($.fn.validatebox.defaults.rules, {
      
        //验证非法关键字
        ValidateKeywords: {
            validator: function (value, param) {
                
                var arr = keywords.split('|');

                var m = 0;
                if (arr.length > 1) {
                    for (i = 0; i < arr.length; i++) {

                        if (value.indexOf(arr[i]) != -1) {

                            break;
                        }
                        m++;
                    }
                } else {
                    return true;
                }
                return arr.length==m;
            },
            message: '文字中不能包含特殊关键字'
        },

        // 验证Grid行编辑器Combo和ComboBox的值，根据选中值来验证，而非文本框的值
        // 参数：ChildGridID,FieldID
        gridSelectionRequired: {
            validator: function (value, param) {
                if (!param || param.length <= 1) {
                    return false;
                }

                var grid = $('#' + param[0]);
                if (!grid || grid.length <= 0) {
                    return false;
                }

                var editingIndex = grid[0].exEditingRowIndex;
                if (editingIndex == undefined || editingIndex == null || editingIndex < 0) {
                    return true;
                }

                var editor = grid.datagrid('getEditor', { index: editingIndex, field: param[1] });
                if (!editor || !editor.target || editor.target.length <= 0) {
                    return true;
                }

                var selectValue = parseInt(editor.target.combobox('getValue'));
                if (!selectValue || selectValue <= 0) {
                    return false;
                }

                if ($(editor.target[0].parentNode).find('.combotree-f').length > 0) {
                    var findNode = editor.target.combotree("tree").tree('find', selectValue);
                    if (findNode && findNode.text == editor.target.combobox('getText')) {
                        return true;
                    }
                }
                else {
                    var data = editor.target.combobox('getData');
                    if (!data || !data.getSelectionByValue) {
                        return false;
                    }

                    var selectItem = data.getSelectionByValue(selectValue);
                    if (selectItem && selectItem.text == editor.target.combobox('getText')) {
                        return true;
                    }
                }

                return false;
            },
            message: '请选择'
        },

        // 验证Grid行编辑器在Grid本行中的依赖项是否有值
        // 参数：ChildGridID,CurrentFieldID,DependFieldName,DependFieldDisplayName
        gridDependRequired: {
            validator: function (value, param) {
                if (!param || param.length <= 3) {
                    return false;
                }

                var grid = $('#' + param[0]);
                if (!grid || grid.length <= 0) {
                    return false;
                }

                var dependItem = param[2];
                var dependControl = grid.datagrid('exGetControl', dependItem);
                if (!dependControl) {
                    return true;
                }

                var currentItem = param[1];
                var currentControl = grid.datagrid('exGetControl', currentItem);

                // 暂时只支持combo类型的依赖栏位
                var dependValue = $(dependControl).combo('getValue');
                if (amCommon.notEmpty(dependValue)) {
                    if (currentControl) {
                        currentControl.exDependItemValue = dependValue;
                    }
                    return true;
                }
                else {
                    if (currentControl) {
                        currentControl.exDependItemValue = null;
                    }
                    return false;
                }
            },
            message: '请先填写本行的【{3}】栏位'
        },

        // 验证Grid行编辑器在主表单Form中的依赖项是否有值
        // 参数：ChildGridID,CurrentFieldID,DependFieldName,DependFieldDisplayName
        gridDependFormRequired: {
            validator: function (value, param) {
                if (!param || param.length <= 3) {
                    return false;
                }

                var grid = $('#' + param[0]);
                if (!grid || grid.length <= 0) {
                    return false;
                }

                var currentItem = param[1];
                var currentControl = grid.datagrid('exGetControl', currentItem);

                var dependItem = param[2];
                var dependValue = eval('(viewModel.form.' + dependItem + ') ? viewModel.form.' + dependItem + '() : null');
                if (amCommon.notEmpty(dependValue)) {
                    if (currentControl) {
                        currentControl.exDependItemValue = dependValue;
                    }
                    return true;
                }
                else {
                    if (currentControl) {
                        currentControl.exDependItemValue = null;
                    }
                    return false;
                }
            },
            message: '请先填写主表单的【{3}】栏位'
        },

        // 参数：ChildGridID,CompareFieldName,CompareFieldDisplayName
        gridDateLessOrEqual: {
            validator: function (value, param) {
                if (!param || param.length <= 1) {
                    return false;
                }

                var grid = $('#' + param[0]);
                if (!grid || grid.length <= 0) {
                    return false;
                }

                var compareItem = param[1];
                var compareControl = grid.datagrid('exGetControl', compareItem);
                if (!compareControl) {
                    return true;
                }

                var compareValue = $(compareControl).datebox('getValue');
                if (!amCommon.notEmpty(value) || !amCommon.notEmpty(compareValue)) {
                    return true;
                }
                else {
                    if (Date.prototype.compare(value, compareValue) <= 0) {
                        return true;
                    }
                }

                return false;
            },
            message: '值必须小于等于【{2}】栏位'
        },

        // 参数：ChildGridID,CompareFieldName,CompareFieldDisplayName
        gridDateGreaterOrEqual: {
            validator: function (value, param) {
                if (!param || param.length <= 1) {
                    return false;
                }

                var grid = $('#' + param[0]);
                if (!grid || grid.length <= 0) {
                    return false;
                }

                var compareItem = param[1];
                var compareControl = grid.datagrid('exGetControl', compareItem);
                if (!compareControl) {
                    return true;
                }

                var compareValue = $(compareControl).datebox('getValue');
                if (!amCommon.notEmpty(value) || !amCommon.notEmpty(compareValue)) {
                    return true;
                }
                else {
                    if (Date.prototype.compare(value, compareValue) >= 0) {
                        return true;
                    }
                }

                return false;
            },
            message: '值必须大于等于【{2}】栏位'
        }
    });

})(jQuery);

var editGridHandler = function (jqGrid, childGridMeta, childData, disable) {
    var me = this;
    var grid = jqGrid;
    var editIndex = undefined;
    var comboMetaData = {};
    var changeHandlers = {};
    var extraFilters = {};

    // 传入的主表参数
    var referedParentRecordID = data.FormData.ReferedRecordID;
    var referedParentTableID = data.FormData.ReferedTableID;
    var parentFormName = data.FormData.FormName;
    var parentViewModelForm = viewModel.form;

    // 传入的本子表参数
    var metadata = childGridMeta.ItemMetadata;
    var defaultData = childData.ItemData;
    var childFormID = childData.FormID;
    var childFormName = childData.FormName;
    var childReferedTableID = childData.ReferedTableID;

    // 对外接口
    this.iFrozenColumns = new Array();
    this.iDisableColumns = new Array();

    // 创建好一个列时引发事件，参数：field（这个对象包括field、editor等属性）
    this.iAfterCreateField = undefined;

    // 添加Change事件，func参数：newValue, itemName, oldValue
    this.fAddChangeHandler = function (itemName, func) {
        if (amCommon.notEmpty(itemName) && typeof (func) == "function") {
            var itemHandlers = changeHandlers[itemName];
            if (!amCommon.isArray(itemHandlers)) {
                changeHandlers[itemName] = new Array();
                itemHandlers = changeHandlers[itemName];
            }

            itemHandlers.push(func);
        }
    };

    // 附加验证规则，传参是整个grid的数据行；返回false表示校验失败，取消保存
    this.fExtraValidation = undefined;

    // 在开始编辑行时引发事件；参数：rowIndex, rowData
    this.exOnBeforeEdit = undefined;

    // 在开始编辑行并且编辑控件已渲染完成时，引发事件；参数：rowIndex, rowData
    this.exOnRenderedEdit = undefined;

    // 在表格数据发生任何变化时引发事件；参数：rowIndex, rowData, changes
    this.exOnAllChange = undefined;

    this.exBeforeAppend = undefined;

    this.exOnAppend = function (rowIndex, rowData) {
        if (me.exOnAllChange) {
            me.exOnAllChange(rowIndex, rowData, undefined);
        }
    };

    this.exOnAfterEdit = function (rowIndex, rowData, changes) {
        if (me.exOnAllChange) {
            me.exOnAllChange(rowIndex, rowData, changes);
        }
    };

    this.exOnDeleteRow = function (rowIndex) {
        if (me.exOnAllChange) {
            me.exOnAllChange(rowIndex, undefined, undefined);
        }
    };

    this.exOnReject = function (rowIndex) {
        if (me.exOnAllChange) {
            me.exOnAllChange(rowIndex, undefined, undefined);
        }
    };

    // 在引用数据加载完成后引发事件，参数rows
    this.exOnLoadReferData = undefined;

    // 子表引用其他表单时，需要使用的依赖项数据
    // 对象属性：ReferDependItemName,ReferDependItemDisplayName,ReferFilterItemID
    this.iReferDependInfo = undefined;

    // 为外键字段的弹出框添加额外过滤条件
    this.fAddExtraFilter = function (itemName, filterStrings) {
        if (amCommon.notEmpty(itemName)) {
            extraFilters[itemName] = filterStrings;
        }
    };

    // 设置当前编辑行的指定单元格，支持numberbox类型
    this.setCellValue = function (itemName, newValue) {
        var control = grid.datagrid('exGetControl', itemName);
        if (control) {
            $(control).numberbox('setValue', newValue);
        }
    };

    // 清空当前编辑行的指定单元格
    this.clearCellValue = function (itemName) {
        var control = grid.datagrid('exGetControl', itemName);
        if (control && control.exComboClear && control.exComboClear.doClearValue) {
            control.exComboClear.doClearValue();
        }
    };

    this.refreshAllRows = function () {
        var rows = grid.datagrid('getRows');
        for (var i = 0; i < rows.length; i++) {
            grid.datagrid('refreshRow', i);
        }
    };

    // 解决行编辑时，一些自动计算列无法及时刷新的问题：目前支持自动更新numberbox、combobox和combogrid列
    function updateRowOnChange(newValue, oldValue, itemName, element) {

        if (editIndex != undefined) {
            var selectedRow = grid.datagrid('getSelected');
            if (!selectedRow) {
                return;
            }
            var selectedIndex = grid.datagrid('getRowIndex', selectedRow);
            if (selectedIndex == undefined || selectedIndex == null || selectedIndex != editIndex) {
                return;
            }

            if (selectedRow[itemName] != undefined && selectedRow[itemName] != null) {
                selectedRow[itemName] = newValue;

                // 同时引发全局Change事件，实现自动计算列的数值计算
                if (me.exOnAllChange) {
                    me.exOnAllChange(selectedIndex, selectedRow, undefined);
                }

                var editorList = grid.datagrid('getEditors', selectedIndex);
                if (!editorList || editorList.length <= 0) {
                    return;
                }

                for (var i = 0; i < editorList.length; i++) {
                    var editor = editorList[i];
                    if (!editor
                        || editor.type != 'numberbox'
                        || editor.field == undefined || editor.field == null
                        || !editor.target) {
                        continue;
                    }

                    var value = selectedRow[editor.field];
                    if (value == undefined || value == null) {
                        continue;
                    }

                    var control = $(editor.target);
                    if (control.length <= 0) {
                        continue;

                    }

                    // 把自动计算列的值刷新到编辑器中
                    control.numberbox('setValue', value);
                    // 对于setValue过的行，datagrid.getChanges不会视为updated，通过手工判断是否updated来解决
                    selectedRow._ExHasChanged = true;

                    // 把光标移到文本最后
                    var activeElement = document.activeElement;
                    if (activeElement
                        && control[0] == activeElement
                        && control[0].createTextRange) {

                        var range = control[0].createTextRange();
                        range.collapse(true);
                        range.moveStart('character', value.toString().length);
                        range.select();
                    }
                }
            }
        }
    };

    function comboTreeOnSelect(item, itemName) {
        if (item) {
            comboOnSelect({ text: item.text, value: item.id }, itemName);
        }
    };

    function comboOnSelect(item, itemName, element) {
        if (item) {
            if (!comboMetaData[itemName]) {
                comboMetaData[itemName] = new Array();
            }
            if (!comboMetaData[itemName].containsSelection(item)) {
                comboMetaData[itemName].push(item);
            }

            if (element) {
                var controlOptions = $(element).combobox("options");
                if (controlOptions) {
                    if (!controlOptions.data || !controlOptions.data.containsSelection) {
                        controlOptions.data = new Array();
                    }

                    if (!controlOptions.data.containsSelection(item)) {
                        controlOptions.data.push(item);
                    }
                }
            }
        }
    };

    function getMultiSelectionTexts(valueInput, optionsData) {
        if (optionsData) {
            if (amCommon.notEmpty(valueInput)) {
                var valueList = valueInput;
                if (!amCommon.isArray(valueList)) {
                    valueList = valueInput.split(',');
                }

                var textList = '';
                for (var j = 0; j < valueList.length; j++) {
                    var value = valueList[j];
                    for (var i = 0; i < optionsData.length; i++) {
                        if (optionsData[i].value == value) {
                            textList += optionsData[i].text + ',';
                            break;
                        }
                    }
                }
                return textList.trim(',');
            }
        }
        return "";
    }

    this.comboLoadMetaFormatter = function (valueInput, row, index) {
        var result = "";
        if (!amCommon.notEmpty(valueInput)) {
            return result;
        }

        var editorOptions = this.editor.options;
        var optionsData = editorOptions.data;
        if (editorOptions.multiple == true) {
            valueInput = valueInput.toString().split(',');
        }

        if (amCommon.isArray(valueInput)) {
            result = getMultiSelectionTexts(valueInput, optionsData);
        }
        else if (optionsData) {
            for (var i = 0; i < optionsData.length; i++) {
                if (optionsData[i].value == valueInput) {
                    result = optionsData[i].text;
                    break;
                }
            }
        }

        if (result == "") {
            result = me.comboStoreMetaFormatter(valueInput, row, index, this);
        }

        return result;
    };

    this.comboStoreMetaFormatter = function (valueInput, row, index, element) {

        if (!element) {
            element = this;
        }

        var result = "";
        if (!amCommon.notEmpty(valueInput)) {
            return result;
        }

        var editorOptions = element.editor.options;
        if (editorOptions.multiple == true) {
            valueInput = valueInput.toString().split(',');
        }

        var itemName = element.field;
        var comboData = comboMetaData[itemName];
        if (amCommon.isArray(valueInput)) {
            result = getMultiSelectionTexts(valueInput, comboData);
        }
        else if (comboData) {
            for (var i = 0; i < comboData.length; i++) {
                if (comboData[i].value == valueInput) {
                    result = comboData[i].text;
                    break;
                }
            }
        }

        if (result == "") {
            // 显示初始数据，不从comboMetaData中读取，而读取DisplayName数据
            var value = row[itemName];
            var displayName = row["_DisplayName_" + itemName];

            if (value != undefined && displayName != undefined) {
                // 并将初始数据加入comboMetaData
                var newMeta = new Array();
                if (amCommon.isArray(value) && amCommon.isArray(displayName)) {
                    for (var i = 0; i < value.length && i < displayName.length; i++) {
                        var item = { text: displayName[i], value: value[i] };
                        newMeta.push(item);
                        comboOnSelect(item, itemName);
                    }

                    result = displayName.join(',');
                }
                else {
                    var item = { text: displayName, value: value };
                    newMeta.push(item);
                    comboOnSelect(item, itemName);
                    result = displayName;
                }

                if (!editorOptions.data || !editorOptions.data.mergeSelections) {
                    editorOptions.data = new Array();
                }

                editorOptions.data = editorOptions.data.mergeSelections(newMeta);
            }
        }

        return result;
    };

    this.multiSelectionFormatter = function (valueInput, row, index, element) {
        if (!element) {
            element = this;
        }

        var result = "";
        var optionsData = element.editor.options.data;
        if (amCommon.isArray(valueInput)) {
            result = getMultiSelectionTexts(valueInput, optionsData);
        }

        return result;
    };

    this.initSerialNumber = function (serialFiedList) {
        if (serialFiedList && serialFiedList.length > 0) {
            var rows = grid.datagrid('getRows');
            for (var i = 0; i < rows.length; i++) {
                var data = rows[i];
                if (!data) {
                    continue;
                }

                for (var j = 0; j < serialFiedList.length; j++) {
                    var serialFied = serialFiedList[j];
                    var cell = data[serialFied];
                    if (cell && cell.length > 1) {
                        grid.datagrid('selectRow', i).datagrid('exEditCell', { index: i, field: serialFied });
                    }
                }
            }
        }
    }

    // mark 不支持多行文本、布尔类型
    this.bindChangeEvents = function (newValue, oldValue, itemName, element, isCombo) {
        var itemMeta = metadata[itemName];

        var comboClear;
        if (isCombo) {
            comboClear = new comboClearFunction(element);
            if (disable != true) {
                comboClear.addClearButton();
            }
            comboClear.showClearButton(newValue);
        }

        var dataTypeInfo = itemMeta.DataTypeInfo;
        switch (dataTypeInfo) {
            default:
                break;

            case 'TypeSinglelineText':
                {
                    updateRowOnChange(newValue, null, itemName, element);
                    break;
                }

            case 'TypeSingleSelect':
            case 'TypeSingleDepartment':
            case 'TypeFlowState':
                {
                    if (!(element.exHasBindKeyup)) {
                        element.exHasBindKeyup = true;
                        $(element).combo('textbox').keyup(function (event) {
                            if (!window.typeKeyIsAction(event.keyCode)) {

                                // 用户手动删除了所有文本时，则把选中值清空
                                comboClear.showClearButton();
                                var newQueryText = $(element).combo("getText");
                                if (newQueryText == undefined
                                    || newQueryText == null
                                    || newQueryText.toString().length <= 0) {

                                    comboClear.doClearValue();
                                }
                            }
                        });
                    }
                    break;
                }

            case 'TypeSingleUser':
                {
                    var comboTextButton = new comboTextButtonFunction(element);
                    comboTextButton.addTextButton();

                    var comboAutoComplete = new comboAutoCompleteFunction(element, comboClear);
                    comboAutoComplete.userAutoComplete();
                    break;
                }

            case 'TypeInteger':
            case 'TypeDecimal':
                {
                    updateRowOnChange(newValue, oldValue, itemName, element);
                    break;
                }

            case 'TypeMultiUser':
                {
                    var comboTextButton = new comboTextButtonFunction(element);
                    comboTextButton.addTextButton();
                    break;
                }

            case 'TypeSingleOneTableFK':
                {
                    var foreignTextItemName = itemMeta.ForeignTextItemName;
                    if (itemMeta.ForeignViewID > 0) {
                        foreignTextItemName = itemMeta.ForeignViewTextItemName;
                    }

                    var comboPopupSelect = new comboPopupSelectFunction(element,
                        itemMeta.ForeignTableID, '', foreignTextItemName);
                    var itemExtraFilter = extraFilters[itemName];
                    comboPopupSelect.iExtraFilter = itemExtraFilter;
                    comboPopupSelect.addPopupSelect();

                    var comboAutoComplete = new comboAutoCompleteFunction(element, comboClear);
                    comboAutoComplete.iExtraFilter = itemExtraFilter;
                    comboAutoComplete.foreignKeyAutoComplete(itemMeta.ForeignTableID, itemMeta.ForeignTextItemName, true);
                    break;
                }

            case 'TypeSerialNumberCreationFK':
                {
                    comboSerialNumberFunction.initControl(element, itemName, disable);
                    break;
                }

            case 'TypeSerialNumberSelectionFK':
                {
                    var comboPopupSelect = new comboPopupSelectFunction(element,
                        itemMeta.ForeignViewID, '', itemMeta.ForeignViewTextItemName);
                    comboPopupSelect.iExtraFilter = extraFilters[itemName];
                    comboPopupSelect.addPopupSelect();
                    break;
                }
        }

        // 执行额外绑定的Change事件处理程序
        if (newValue != oldValue) {
            var itemHandlers = changeHandlers[itemName];
            if (itemHandlers && amCommon.isArray(itemHandlers)) {
                $.each(itemHandlers, function (index, func) {
                    if (typeof (func) == "function") {
                        func(newValue, itemName, oldValue);
                    }
                });
            }
        }
    };

    function createField(itemName, itemCount, editorType) {
        var required = false;
        var itemMeta = metadata[itemName];

        if (itemMeta.IsRequired
            && disable != true
            && itemMeta.EnableEdit) {
            required = true;
        }

        var disabled = false;
        if (!itemMeta.EnableEdit) {
            disabled = true;
        }

        var width = itemMeta.DisplayWidth;
        if (width > 300) {
            width = 300;
        }

        var deltaX = (itemCount <= 0) ? 12 : 2;
        var tipPosition = (itemCount <= 0) ? 'right' : 'left';
        var missingMessage = '必填';

        var field = {
            field: itemName, width: width, title: itemMeta.DisplayName,
            editor: {
                type: editorType,
                options: { width: width, required: required, disabled: disabled, tipPosition: tipPosition, missingMessage: missingMessage, deltaX: deltaX }
            }
        };

        return field;
    }

    function createComboField(itemName, itemCount, editorType) {
        var field = createField(itemName, itemCount, editorType);
        var options = field.editor.options;
        options.textField = 'text';
        options.valueField = 'value';
        options.editable = false;
        return field;
    }

    function createComboGridField(itemName, itemCount) {
        var field = createField(itemName, itemCount, 'combogrid');
        var options = field.editor.options;
        var parentGridID = grid.attr('id');
        options.editable = false;
        options.multiple = true;
        options.textField = 'text';
        options.idField = 'text';
        options.valueField = 'text';
        options.panelWidth = 350;
        options.panelHeight = 250;
        options.rownumbers = true;
        options.onShowPanel = function () {
            comboSerialNumberFunction.initData(this);
        };
        options.onHidePanel = function () {
            comboSerialNumberFunction.saveData(this);
        };

        var fieldWidth = (disable != true) ? 240 : 300;
        options.columns = [[
            {
                field: 'text', title: '序列号', width: fieldWidth, filterable: true, editor: {
                    type: 'validatebox', options: { width: fieldWidth, required: true, tipPosition: 'right', missingMessage: '必填', deltaX: 2, validType: ['length[0,44]', 'serialNumber'] }
                }
            }
        ]];

        if (disable != true) {
            options.showHeader = true;
            options.columns[0].push({
                field: '_Action', title: '操作', width: 60, filterable: false,
                formatter: function (value, row, index) {
                    return comboSerialNumberFunction.formatAction(parentGridID, itemName, index);
                }
            });

            options.toolbar = [
                {
                    text: '批量生成',
                    id: '_ExChildGridToolbar_Multi_' + itemName,
                    iconCls: 'icon-arrow-multi'
                }, {
                    text: '新建',
                    id: '_ExChildGridToolbar_Add_' + itemName,
                    iconCls: 'icon-add'
                }, {
                    text: '清空',
                    id: '_ExChildGridToolbar_Clear_' + itemName,
                    iconCls: 'icon-arrow-clear'
                }
            ];
        }
        else {
            options.showHeader = false;
            options.toolbar = [
              {
                  text: '',
                  id: '_ExChildGridToolbar_Search_' + itemName,
                  iconCls: 'icon-search'
              }
            ];
        }

        return field;
    }

    this.bindEditor = function () {
        var fieldList = [];
        var frozenFieldList = [];
        var serialFiedList = [];
        var itemCount = 0;
        var jqGridID = jqGrid.attr('id');

        for (var itemName in metadata) {
            var itemMeta = metadata[itemName];
            if (!itemMeta.EnableView) {
                continue;
            }

            var gridSelectionRequired = 'gridSelectionRequired["' + jqGridID + '","' + itemName + '"]';
            var gridDependRequired = (itemMeta.DependItemID > 0 && !itemMeta.IsDependParentItem) ? 'gridDependRequired["' + jqGridID + '","' + itemName + '","' + itemMeta.DependItemName + '","' + itemMeta.DependItemDisplayName + '"]' : '';
            var gridDependFormRequired = (itemMeta.DependItemID > 0 && itemMeta.IsDependParentItem == true) ? 'gridDependFormRequired["' + jqGridID + '","' + itemName + '","' + itemMeta.DependItemName + '","' + itemMeta.DependItemDisplayName + '"]' : '';

            var gridValidList = gridSelectionRequired;
            if (amCommon.notEmpty(gridDependFormRequired)) {
                // 顺序不可颠倒，依赖项校验必须在前，保证每次都进行依赖校验
                gridValidList = [gridDependFormRequired, gridSelectionRequired];
            }

            var lenthValid = ''
            if (amCommon.notEmpty(itemMeta.MinLength) || amCommon.notEmpty(itemMeta.MaxLength)) {
                lenthValid = 'length[' + (amCommon.notEmpty(itemMeta.MinLength) ? itemMeta.MinLength : -1) + ',' + (amCommon.notEmpty(itemMeta.MaxLength) ? itemMeta.MaxLength : 10000000) + ']';
            }

            var numberRangeValid = ''
            if (amCommon.notEmpty(itemMeta.MinNumber) || amCommon.notEmpty(itemMeta.MaxNumber)) {
                numberRangeValid = 'numberRange[' + (amCommon.notEmpty(itemMeta.MinNumber) ? itemMeta.MinNumber : '"～"') + ',' + (amCommon.notEmpty(itemMeta.MaxNumber) ? itemMeta.MaxNumber : '"～"') + ']';
            }

            var dataTypeInfo = itemMeta.DataTypeInfo;
            var field = createField(itemName, itemCount, 'validatebox');
            switch (dataTypeInfo) {
                default:
                    field = null;
                    break;

                case 'TypeSinglelineText':
                case 'TypeMultilineText':
                    {
                        var editorOptions = field.editor.options;
                        if (amCommon.notEmpty(lenthValid)) {
                            editorOptions.validType = lenthValid;
                        }
                        editorOptions.exGridItemName = itemName;
                        editorOptions.onChange = function () { me.bindChangeEvents($(this).val(), null, $(this).validatebox('options').exGridItemName, this, false); };
                        break;
                    }

                case 'TypeSingleSelect':
                case 'TypeFlowState':
                    {
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.comboLoadMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.data = itemMeta.EnumValues;
                        editorOptions.editable = true;
                        editorOptions.validType = gridSelectionRequired;
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeMultiSelect':
                    {
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.multiSelectionFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.data = itemMeta.EnumValues;
                        editorOptions.multiple = true;
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeDatetime':
                    {
                        field = createField(itemName, itemCount, 'datebox');
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.editable = false;
                        editorOptions.align = 'right';
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).datebox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeBoolean':
                    {
                        var caseBooleanItem = itemName;
                        field = createField(caseBooleanItem, itemCount, 'checkbox');
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.width = undefined;
                        editorOptions.on = 'true';
                        editorOptions.off = 'false';
                        field.formatter = function (val, row, index) {
                            var result = '';
                            if (val == true || val == "true" || val == "yes"
                                || val == "1" || val == "是" || val == "√") {
                                result = '√';
                            }
                            return result;
                        }
                        break;
                    }

                case 'TypeInteger':
                    {
                        field = createField(itemName, itemCount, 'numberbox');
                        var editorOptions = field.editor.options;

                        if (amCommon.notEmpty(numberRangeValid)) {
                            editorOptions.validType = numberRangeValid;
                        }
                        editorOptions.exGridItemName = itemName;
                        editorOptions.align = 'right';
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).numberbox('options').exGridItemName, this, false); };
                        break;
                    }

                case 'TypeDecimal':
                    {
                        var precision = (itemMeta.DecimalLength > 0) ? itemMeta.DecimalLength : 0;
                        field = createField(itemName, itemCount, 'numberbox');
                        var editorOptions = field.editor.options;

                        if (amCommon.notEmpty(numberRangeValid)) {
                            editorOptions.validType = numberRangeValid;
                        }
                        editorOptions.exGridItemName = itemName;
                        editorOptions.align = 'right';
                        editorOptions.precision = precision;
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).numberbox('options').exGridItemName, this, false); };
                        break;
                    }

                case 'TypeSingleDepartment':
                    {
                        field = createComboField(itemName, itemCount, 'combotree');
                        field.formatter = me.comboStoreMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.editable = true;
                        editorOptions.validType = gridSelectionRequired;
                        editorOptions.url = '/api/AuthorityDepartment/List?IsSelect=1';
                        editorOptions.onSelect = function (node) { comboTreeOnSelect(node, $(this).tree('options').exGridItemName); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combotree('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeMultiDepartment':
                    {
                        field = createComboField(itemName, itemCount, 'combotree');
                        field.formatter = me.comboStoreMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.multiple = true;
                        editorOptions.checkbox = true;
                        editorOptions.cascadeCheck = false;
                        editorOptions.url = '/api/AuthorityDepartment/List?IsSelect=1';
                        editorOptions.onSelect = function (node) { comboTreeOnSelect(node, $(this).tree('options').exGridItemName); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combotree('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeSingleUser':
                    {
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.comboLoadMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.data = itemMeta.EnumValues;// 解决编辑框无法正常显示的问题
                        editorOptions.editable = true;
                        editorOptions.validType = gridSelectionRequired;
                        editorOptions.onSelect = function (node) { comboOnSelect(node, $(this).combobox('options').exGridItemName, this); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeMultiUser':
                    {
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.comboLoadMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.data = itemMeta.EnumValues;
                        editorOptions.readonly = true;
                        editorOptions.multiple = true;
                        editorOptions.onSelect = function (node) { comboOnSelect(node, $(this).combobox('options').exGridItemName, this); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeSingleOneTableFK':
                    {
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.comboLoadMetaFormatter;
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.foreignTableUrl = itemMeta.ForeignTableUrl;
                        editorOptions.foreignViewID = itemMeta.ForeignViewID;
                        editorOptions.dependItemID = itemMeta.DependItemID;
                        editorOptions.dependDecideItemID = itemMeta.DependDecideItemID;
                        editorOptions.dependDecideSummaryItemID = itemMeta.DependDecideSummaryItemID;
                        editorOptions.data = itemMeta.EnumValues;
                        editorOptions.editable = true;
                        editorOptions.validType = gridValidList;
                        editorOptions.onSelect = function (node) { comboOnSelect(node, $(this).combobox('options').exGridItemName, this); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeSerialNumberCreationFK':
                    {
                        serialFiedList.push(itemName);
                        field = createComboGridField(itemName, itemCount);
                        var editorOptions = field.editor.options;

                        editorOptions.exGridItemName = itemName;
                        editorOptions.validType = gridDependRequired;
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combogrid('options').exGridItemName, this, true); };
                        break;
                    }

                case 'TypeSerialNumberSelectionFK':
                    {
                        serialFiedList.push(itemName);
                        field = createComboField(itemName, itemCount, 'combobox');
                        field.formatter = me.comboLoadMetaFormatter;

                        var editorOptions = field.editor.options;
                        editorOptions.exGridItemName = itemName;
                        editorOptions.foreignViewID = itemMeta.ForeignViewID;
                        editorOptions.dependItemID = itemMeta.DependItemID;
                        editorOptions.dependDecideItemID = itemMeta.DependDecideItemID;
                        editorOptions.dependDecideSummaryItemID = itemMeta.DependDecideSummaryItemID;
                        editorOptions.data = itemMeta.EnumValues;
                        editorOptions.readonly = true;
                        editorOptions.multiple = true;
                        editorOptions.validType = gridDependRequired;
                        editorOptions.onSelect = function (node) { comboOnSelect(node, $(this).combobox('options').exGridItemName, this); };
                        editorOptions.onChange = function (newValue, oldValue) { me.bindChangeEvents(newValue, oldValue, $(this).combobox('options').exGridItemName, this, true); };

                        me.fAddChangeHandler(itemMeta.DependItemName, eval('(function () { viewModel.gridEditors.' + childFormName + '.clearCellValue("' + itemName + '") })'));
                        break;
                    }
            }

            if (field != null) {
                itemCount++;

                if (me.iAfterCreateField) {
                    me.iAfterCreateField(field);
                }

                if (me.iDisableColumns && me.iDisableColumns.contains(itemName)) {
                    field.editor.options.disabled = true;
                }

                if (me.iFrozenColumns && me.iFrozenColumns.contains(itemName)) {
                    frozenFieldList.push(field);
                }
                else {
                    fieldList.push(field);
                }
            }
        }

        var fitColumns = (itemCount >= 10) ? false : true;
        var options = {
            fitColumns: fitColumns,
            onClickRow: me.beginEditing,
            onBeforeEdit: me.exOnBeforeEdit,
            exOnRenderedEdit: me.exOnRenderedEdit,
            onAfterEdit: me.exOnAfterEdit
        };

        if (fieldList.length > 0) {
            options.columns = [fieldList];
        }

        if (frozenFieldList.length > 0) {
            options.frozenColumns = [frozenFieldList];
        }

        if (disable == true && serialFiedList.length > 0) {
            options.onLoadSuccess = function (data) {
                me.initSerialNumber(serialFiedList);
            };
        }

        grid.datagrid(options);
    };

    this.loadData = function () {
        if (referedParentRecordID > 0) {
            // 默认为复制本表
            var referedTableID = -1;

            if (referedParentTableID > 0) {
                if (childReferedTableID > 0) {
                    // 大于零表示引用子表
                    referedTableID = childReferedTableID;
                }
                else {
                    // 没有可引用的子表
                    return;
                }
            }

            var url = '/api/ListData/DetailListReferTable?MasterTableID=' + childFormID +
                '&ReferedTableID=' + referedTableID + '&ReferedParentRecordID=' + referedParentRecordID;

            me.loadReferData(url);
        }
        else {
            var url = jqGrid.attr('exUrl');
            if (url) {
                // 编辑数据
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json"
                })
                .success(function (result) {
                    if (result && result.rows) {
                        grid.datagrid('loadData', result);
                    } else {
                        $.messager.alert('提示', result, 'error');
                    }

                    // 解决Datagrid无数据时不显示横向滚动条的问题
                    if (!result || !(result.rows) || result.rows.length <= 0) {
                        var width = grid.prev(".datagrid-view2").find(".datagrid-header-row").width();
                        if (width > 0) {
                            grid.prev(".datagrid-view2").children(".datagrid-body").html("<div style='width:" + width + "px;border:solid 0px;height:1px;'></div>");
                        }
                    }
                })
                .error(function (result) {
                    $.messager.alert('提示', result.responseText, 'error');
                });
            } else {
                var urlRefered = jqGrid.attr('exUrlRefered');
                if (urlRefered) {
                    me.loadReferData(urlRefered, undefined, true);
                }
            }
        }
    };

    function initComboControl(editIndex, rowData) {
        // 对于部门、用户、外键数据等栏位，无默认值时无法初始化，通过强行应发Change事件初始化控件
        var editorList = grid.datagrid('getEditors', editIndex);
        if (!rowData || !editorList || editorList.length <= 0) {
            return;
        }

        for (var i = 0; i < editorList.length; i++) {
            var editor = editorList[i];
            if (!editor
                || (editor.type != 'combobox' && editor.type != 'combotree')
                || editor.field == undefined || editor.field == null
                || !editor.target || editor.target.length <= 0) {
                continue;
            }

            var value = rowData[editor.field];
            if (!amCommon.notEmpty(value)) {
                me.bindChangeEvents('', '', editor.field, editor.target[0], true);
            }
        }
    }

    this.loadReferData = function(url, param, removeExValid) {
        $.ajax({
            type: "POST",
            url: url,
            data: param
        })
        .success(function (result) {
            if (!result || !result.rows) {
                $.messager.alert('提示', result, 'error');
                return;
            }

            if (result.rows.length <= 0) {
                return;
            }

            if (me.exOnLoadReferData) {
                me.exOnLoadReferData(result.rows);
            }

            // 将引用的行加载到Grid
            var startIndex = grid.datagrid('getRows').length;
            for (var i = 0; i < result.rows.length; i++) {
                if (startIndex >= 100) {
                    break;
                }

                // 只拷贝引用的字段，其他字段采用默认值
                var referRow = result.rows[i];
                referRow.ID = "";
                referRow._ID = "";
                if (!referRow || !amCommon.isObject(referRow) || referRow.length <= 0) {
                    continue;
                }

                var rowData = JSON.parse(JSON.stringify(defaultData));
                if (!removeExValid) {
                    rowData._ExNeedValid = true;
                }
                for (var itemName in referRow) {
                    rowData[itemName] = referRow[itemName];
                }
                
                grid.datagrid('appendRow', rowData);
                if (me.exOnAppend) {
                    me.exOnAppend(startIndex, rowData);
                }

                // 刷新自动计算列
                grid.datagrid('refreshRow', startIndex);

                if (i == 0 && me.endEditing()) {
                    // 尝试开始第一行的编辑
                    me.beginEditing(0);
                }

                startIndex++;
            }
        })
        .error(function (result) {
            $.messager.alert('提示', result.responseText, 'error');
        });
    }

    this.showReferDialog = function (referedViewID, referedViewName) {
        // 依赖项校验
        var filterItemValue;
        var filterItemID;
        var referDependInfo = me.iReferDependInfo;
        if (referDependInfo != null
            && amCommon.notEmpty(referDependInfo.ReferDependItemName)
            && amCommon.notEmpty(referDependInfo.ReferDependItemDisplayName)
            && referDependInfo.ReferFilterItemID > 0
            && parentViewModelForm != null) {

            var parentForm = parentViewModelForm;
            var dependItem = referDependInfo.ReferDependItemName;
            filterItemValue = eval('(parentForm.' + dependItem + ') ? parentForm.' + dependItem + '() : null');

            if (amCommon.notEmpty(filterItemValue)) {
                filterItemID = referDependInfo.ReferFilterItemID;
            }
            else {
                $.messager.alert('提示', '请先填写主表单的【' + referDependInfo.ReferDependItemDisplayName + '】栏位', 'warning');
                return false;
            }
        }

        var newLayer = window.showSummaryDialog(referedViewID, referedViewName, null, filterItemID, filterItemValue, 'MultiReferCopy');
        newLayer.rejectSelectValue = function () {
            // 关闭选择引用记录的对话框
            top.closeDialog();
        };

        newLayer.updatePopupSelectValue = function (oneceSelectedRows, isUnSelect, keepPopupWindow, allSelectedRows, pageFilters) {
            if (keepPopupWindow) {
                return;
            }

            // 关闭选择引用记录的对话框
            top.closeDialog();

            // 异步获取引用的记录
            if (allSelectedRows && allSelectedRows.length > 0) {
                var idList = '';
                for (var i = 0; i < allSelectedRows.length; i++) {
                    idList += allSelectedRows[i]._ID + ',';
                }
                idList = idList.trimEnd(',');

                if (amCommon.notEmpty(pageFilters)) {
                    pageFilters = ',' + pageFilters;
                }
                else {
                    pageFilters = '';
                }
                var param = 'filterRules=[{"field":"_ID","op":"idinarray","value":"' + idList + '"}' + pageFilters + ']';
                var url = '/api/ListData/DetailListReferView?MasterTableID=' + childFormID + '&ReferedViewID=' + referedViewID;

                me.loadReferData(url, param);
            }
        };
    };

    // 结束当前行的编辑行为
    this.endEditing = function () {
        if (editIndex == undefined) {
            return true;
        }

        var validResult = grid.datagrid('validateRow', editIndex);
        if (validResult) {
            var selectedRow = grid.datagrid('getSelected');
            if (selectedRow) {
                selectedRow._ExNeedValid = undefined;
            }

            grid.datagrid('endEdit', editIndex);
            jqGrid[0].exEditingRowIndex = undefined;
            editIndex = undefined;

            return true;
        } else {
            return false;
        }
    };

    this.beginEditing = function (index) {
        var result = false;
        if (disable != true) {
            if (editIndex != index) {
                if (me.endEditing()) {
                    grid.datagrid('selectRow', index).datagrid('beginEdit', index);
                    jqGrid[0].exEditingRowIndex = index;
                    editIndex = index;

                    var selectedRow = grid.datagrid('getSelected');
                    initComboControl(editIndex, selectedRow);

                    result = true;
                } else {
                    grid.datagrid('selectRow', editIndex);
                }
            }
            else {
                result = true;
            }
        }

        return result;
    };

    this.append = function (rowData) {
        if (me.exBeforeAppend) {
            if (me.exBeforeAppend(editIndex, rowData) == false) {
                return;
            }
        }

        if (me.endEditing()) {
          
            if (!rowData) {
                // 复制一份行初始数据
                rowData = JSON.parse(JSON.stringify(defaultData));

                // 更新行初始数据，使得新行显示刚刚输入过的数据
                //defaultData = rowData;
            }
            
            grid.datagrid('appendRow', rowData);
            editIndex = grid.datagrid('getRows').length - 1;
            grid.datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
            jqGrid[0].exEditingRowIndex = editIndex;

            if (me.exOnAppend) {
                me.exOnAppend(editIndex, rowData);
            }

            initComboControl(editIndex, rowData);
        }
    };

    this.removeAll = function (showConfirm) {
        function doRemoveAll() {
            if (editIndex >= 0) {
                grid.datagrid('cancelEdit', editIndex);

                jqGrid[0].exEditingRowIndex = undefined;
                editIndex = undefined;
            }

            grid.datagrid('loadData', { total: 0, rows: [] });

            if (me.exOnDeleteRow) {
                me.exOnDeleteRow(editIndex);
            }
        }

        if (showConfirm) {
            $.messager.confirm('删除确认', '确实要删除该记录？', function (r) {
                if (r) {
                    doRemoveAll();
                }
            });
        }
        else {
            doRemoveAll();
        }
    };

    this.removeit = function () {
       
        if (editIndex == undefined) {
            $.messager.alert('提示', '请选择需要删除的记录！', 'warning');
            return;
        }

        $.messager.confirm('删除确认', '确实要删除该记录？', function (r) {
            if (r) {
                grid.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
                if (me.exOnDeleteRow) {
                    me.exOnDeleteRow(editIndex);
                }

                jqGrid[0].exEditingRowIndex = undefined;
                editIndex = undefined;
            }
        });
    };

    this.reject = function () {
        $.messager.confirm('撤销确认', '确实要撤销该表格的所有更改？', function (r) {
            if (r) {
                grid.datagrid('rejectChanges');
                if (me.exOnReject) {
                    me.exOnReject(editIndex);
                }

                jqGrid[0].exEditingRowIndex = undefined;
                editIndex = undefined;
            }
        });
    };

    this.validData = function () {
        if (!me.endEditing()) {
            return false;
        }

        // 对于引用或复制的数据，需要校验是否有效
        var inserted = grid.datagrid('getChanges', "inserted");
        if (inserted && inserted.length > 0) {
            for (var i = 0; i < inserted.length; i++) {
                var row = inserted[i];
                if (!row || !row._ExNeedValid) {
                    continue;
                }

                var rowIndex = grid.datagrid('getRowIndex', row);
                if (rowIndex == undefined || rowIndex == null || rowIndex < 0) {
                    continue;
                }

                if (me.beginEditing(rowIndex)) {
                    if (!me.endEditing()) {
                        return false;
                    }
                }
            }
        }

        // 执行附加验证规则
        if (me.fExtraValidation && typeof (me.fExtraValidation) == "function") {
            if (!me.fExtraValidation(grid.datagrid('getRows'))) {
                return false;
            }
        }

        return true;
    };

    this.getChanges = function () {
        var allRows = grid.datagrid('getRows');
        var deleted = grid.datagrid('getChanges', "deleted");
        var updated = grid.datagrid('getChanges', "updated");
        var inserted = grid.datagrid('getChanges', "inserted");
        var unchanged = [];

        if (allRows && allRows.length > 0) {
            for (var i = 0; i < allRows.length; i++) {
                var row = allRows[i];

                // 排除新增的行
                if (!row
                    || !amCommon.notEmpty(row._ID)
                    || !(Number(row._ID) > 0)) {
                    continue;
                }

                // 排除被删除的行
                var isDeleted = false;
                if (deleted && deleted.length > 0) {
                    for (var j = 0; j < deleted.length; j++) {
                        if (row._ID == deleted[j]._ID) {
                            isDeleted = true;
                            break;
                        }
                    }

                    if (isDeleted) {
                        continue;
                    }
                }

                // 排除已视为更新的行
                var isUpdated = false;
                if (updated && updated.length > 0) {
                    for (var j = 0; j < updated.length; j++) {
                        if (row._ID == updated[j]._ID) {
                            isUpdated = true;
                            break;
                        }
                    }

                    if (isUpdated) {
                        continue;
                    }
                }

                if (row._ExHasChanged == true) {
                    // 对于setValue过的行，datagrid.getChanges不会视为updated，通过手工判断是否updated来解决
                    updated.push(row);
                }
                else {
                    // 采集未修改的行，也需要传入后台进行级联操作
                    unchanged.push(row);
                }
            }
        }

        // 从updated中移除删除的行
        if (updated && deleted) {
            for (var i = updated.length - 1; i >= 0; i--) {
                var row = updated[i];
                for (var j = 0; j < deleted.length; j++) {
                    if (row._ID == deleted[j]._ID) {
                        updated.splice(i, 1);
                        break;
                    }
                }
            }
        }

        var changes = { 'deleted': deleted, 'updated': updated, 'inserted': inserted, 'unchanged': unchanged };
        return changes;
    };

    $(function () {
        me.bindEditor();
        me.loadData();
    });
}